package com.helpfuctions.gcards;

import java.io.InputStream;
import java.util.ArrayList;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Contacts;
import android.util.Log;

public class ContactsList{
	private ArrayList<Contact> mContactsList;
	private ContentResolver mContentResolver;
	public ContactsList(ContentResolver contResolver) {
		mContentResolver = contResolver;
	}
	public ArrayList<Contact> getContacts(){
		Cursor contactCursor = mContentResolver.query(ContactsContract.Contacts.CONTENT_URI,
								new String[]{Contacts._ID, 
								Contacts.DISPLAY_NAME}, null, null, null);
		mContactsList = new ArrayList<Contact>();
		while(contactCursor.moveToNext()){
			Long id = contactCursor.getLong(0);
			String idString = id.toString();
			String displayName = contactCursor.getString(1);			
			
			Cursor mailCursor = mContentResolver.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,
								new String[]{ContactsContract.CommonDataKinds.Email.DATA}, 
								ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?", 
								new String[]{idString}, null); 
			while (mailCursor.moveToNext()) {
				String mail = mailCursor.getString(0);
				Contact adressbook;
				if ((null != mail) & (0 != mail.length())) {
					try {
						Bitmap image = loadImage(id);
						adressbook = new Contact(mail, displayName, image);
						mContactsList.add(adressbook);
						Log.d("id = " + id, " Display name = " + displayName + "");
						Log.d("Mail = ", mail);
					} catch (Exception e) {
						Log.d("CREATE_ARRAY", e.toString());
					}
				}
			}
		}
		return mContactsList;
	}
	
	private Bitmap loadImage(Long contactId) {
		Uri contactPhotoUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId);
		InputStream photoDataStream = Contacts.openContactPhotoInputStream(mContentResolver, contactPhotoUri);
		Bitmap photo = BitmapFactory.decodeStream(photoDataStream);
    return photo;
	}
}
